window.speak = new Vue({
    el: '#speak',
    data() {
        return {
            second: 0,//
            time: '00:00:00',//做题时长
            interVal: '',//
            isFull: false,//是否全屏
            isPop: true,//顶部提示
            questionData: '',//题目数据
            current: 0,//当前题目序号
            p_id: '',//当前题目pid
            content_id: '',//当前题目id
            content_btn_status: '',//当前小题目 方形 圆形
            left: '',//
            display: 'none',//
            isEquip: false,//设备提示
            G_media: '',//录音对象
            waveObj: '',//波浪对象
            recordStatus: -1,//载入-1  录音状态  0  初始化检测音频可用不  1 录音中  2 录音完成  3上传中  4  上传成功
            isPlay: false,
            isUpload: false,//音频是否上传
            againAsk: false,//询问是否重新答题
            audioUrl: '',//录音音频临时地址 https://toefl.viplgw.cn/files/attach/file/20180110/1515565795270505.mp3
            upUrl: '',//上传成功之后后台返回地址
            currentTime: '00:00:00',//音频当前
            totalTime: '00:00:00',//音频总时长
            recordedAudio: null,
            mediaRecorder: null,
            chunks: []
        }
    },
    mounted() {
        let that = this;
        that.$nextTick(function () {
            //初始化音频
            that.audio = $('#bgAudio')[0];
            console.log(' that.audio', that.audio);
            // that.addListen();

            //初始化波浪效果
            that.waveInit();
            //初始化录音功能
            if (window.location.href.indexOf('https') == -1 && window.location.href.indexOf('localhost') == -1) {
                alert('HTTP不支持音视频！！');
                // window.history.go(-1);
            } else {
                // that.mediaInit();
            }


        });
    },
    methods: {
        //波浪初始化
        waveInit() {
            let that = this;
            that.waveObj = new SineWaves({
                el: document.getElementById('waves'),

                speed: 4,

                width: function () {
                    return $(window).width();
                },

                height: function () {
                    return 200;
                },

                ease: 'SineInOut',

                wavesWidth: '80%',

                waves: [{}],

                set1: [{
                    timeModifier: 4,
                    lineWidth: 2,
                    amplitude: -100,
                    wavelength: 0
                }, {
                    timeModifier: 4,
                    lineWidth: 1,
                    amplitude: -50,
                    wavelength: 0
                }],

                set2: [{
                    timeModifier: 4,
                    lineWidth: 2,
                    amplitude: -100,
                    wavelength: 25
                }, {
                    timeModifier: 4,
                    lineWidth: 1,
                    amplitude: -50,
                    wavelength: 20
                }],

                set3: [{
                    timeModifier: 1,
                    lineWidth: 2,
                    amplitude: -180,
                    wavelength: 50,
                    type: 'Triangle',
                    segmentLength: 1
                }],

                initialize: function () {

                    // this.options.startWaves.call(this, 'set2');

                    // var self = this;
                    // self.options.startWaves.call(self, 'set1');  //直线
                    // self.options.startWaves.call(self, 'set2');  //波浪线
                    // self.options.startWaves.call(self, 'set3');  //不知名曲线

                },

                startWaves: function (waves) {
                    this.waves = this.options[waves];
                    this.options.resizeEvent.call(this);
                    this.setupWaveFns();
                },

                // Resize
                resizeEvent: function () {
                    var gradient = this.ctx.createLinearGradient(0, 0, this.width, 0);
                    gradient.addColorStop(0, "rgba(127, 125, 248, 1)");

                    var index = -1;
                    var length = this.waves.length;
                    while (++index < length) {
                        this.waves[index].strokeStyle = gradient;
                    }

                    // Clean Up
                    index = void 0;
                    length = void 0;
                    gradient = void 0;
                }
            });
        },
        //  开始录音
        startRecord() {
            let that = this;
            //此时先显示为录音准备中
            // that.waveObj.options.startWaves.call(that.waveObj, 'set1');
            that.recordStatus = 0;
            //接着检查录音是否支持
            navigator.mediaDevices.getUserMedia({
                audio: true,
                video: false,
            }).then(stream => {
                navigator.mediaDevices.enumerateDevices().then((devices) => {
                    console.log('device', devices);
                    //此时录音权限打开  麦克风正常  可以开始录音
                    // that.waveObj.options.startWaves.call(that.waveObj, 'set2');
                    that.recordStatus = 1;
                    this.mediaRecorder = new MediaRecorder(stream);
                    this.mediaRecorder.addEventListener('dataavailable', this.handleDataAvailable);
                    this.mediaRecorder.start();
                    // that.G_media.startRecording();

                }).catch(function (err) {
                    console.log(err.name + ": " + err.message);
                    that.isEquip = true;
                    that.recordStatus = -1;
                });
            }).catch(function (err) {
                console.log(err);
                that.isEquip = true;
                that.recordStatus = -1;
            });

        },
        //  停止录音
        stopRecord() {
            // let that = this;
            // that.waveObj.options.startWaves.call(that.waveObj, 'set1');
            // that.G_media.stopRecordings();
            this.recordStatus = 2;
            this.mediaRecorder.stop();
        },
        //上传录音
        upload() {
            var that = this
            // this.G_media.uploadAudio();
            const blob = new Blob(this.chunks, {type: 'audio/mpeg'});
            const formData = new FormData();
            console.log('blob', blob)
            formData.append('file', blob,);
            formData.append("filename", 'upload_file.mp3');
            formData.append("client", 'html5');
            // 发送音频数据到后端的API接口
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener("progress", function (e) {
            }, false);
            xhr.addEventListener("load", function (e) {
                console.log(e)
                var data = $.parseJSON(e.target.responseText);
                if (data.code == 1) {
                    that.upUrl = data.file;//录音浏览器后台正式地址
                    that.recordStatus = 4;//上传成功
                    that.isUpload = true;

                } else {
                    that.recordStatus = 2;
                    alert(data.message);
                }
            }, false);
            xhr.addEventListener("error", function (e) {
            }, false);
            xhr.addEventListener("abort", function (e) {
            }, false);
            xhr.open("POST", '/cn/evaluation/up-spoken-audio');
            xhr.send(formData);
            // $.post('/cn/exercise/upload-speak-audio', formData,)
            //     .then(response => {
            //         // 处理后端返回的响应
            //     })
            //     .catch(error => {
            //         // 处理请求错误
            //     });
        },
        //  播放/暂停音频
        playAudio() {

            var audio = this.$refs.audioPlayer;
            var that = this;
            if (!that.isPlay) {
                audio.play();
            } else {
                audio.pause();
            }
            that.isPlay = !that.isPlay;
            // this.$refs.audioPlayer.play();

            audio.addEventListener("onloadedmetadata ", function () {
                console.log('audio', audio.duration)
                that.totalTime = that.formateSeconds(audio.duration);
                // that.audio.volume = 0.7;
                console.log('that.totalTime ', that.totalTime)
            });
            audio.addEventListener("play", function () {

            });
            audio.addEventListener("playing", function (event) {
                that.isPlay = true;
            });
            audio.addEventListener("pause", function () {

            });
            audio.addEventListener("ended", function () {
                that.isPlay = false;
            });
            audio.addEventListener("timeupdate", function (event) {
                console.log('audio timeupdate', audio.duration)
                that.totalTime = that.formateSeconds(audio.duration);
                that.currentTime = that.formateSeconds(audio.currentTime);
            });
        },
        handleDataAvailable(event) {
            this.chunks.push(event.data);
            if (this.mediaRecorder.state === 'inactive') {
                this.processRecordedAudio();
            }
        },
        processRecordedAudio() {
            const blob = new Blob(this.chunks, {type: 'audio/webm'});
            this.recordedAudio = URL.createObjectURL(blob);
            this.$refs.audioPlayer.src = this.recordedAudio;
        },
        //时间转换
        formateSeconds(endTime) {
            let secondTime = parseInt(endTime);//将传入的秒的值转化为Number
            let min = 0;// 初始化分
            let h = 0;// 初始化小时
            let result = '';
            if (secondTime > 60) {//如果秒数大于60，将秒数转换成整数
                min = parseInt(secondTime / 60);//获取分钟，除以60取整数，得到整数分钟
                secondTime = parseInt(secondTime % 60);//获取秒数，秒数取佘，得到整数秒数
                if (min > 60) {//如果分钟大于60，将分钟转换成小时
                    h = parseInt(min / 60);//获取小时，获取分钟除以60，得到整数小时
                    min = parseInt(min % 60);//获取小时后取佘的分，获取分钟除以60取佘的分
                }
            }
            result = `${h.toString().padStart(2, '00')}:${min.toString().padStart(2, '00')}:${secondTime.toString().padStart(2, '00')}`;
            return result;
        },
    }
})
